package com.db.httpserver;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.*;

public final class WorkerThread implements Runnable {

    private Socket socket;

    public static void startPool(int suggestedPort) throws IOException {
        Parameter.setPort(suggestedPort);
        Parameter.print();
        int port = Parameter.getPort();
        int workers = Parameter.getWorkers();
        int timeout = Parameter.getTimeout();

        ExecutorService executor = Executors.newFixedThreadPool(workers);

        ServerSocket serverSocket = new ServerSocket(port);
        Socket socket;
        while (true) {
            socket = serverSocket.accept();
            socket.setSoTimeout(timeout);
            Runnable workerThread = new WorkerThread(socket);

            executor.execute(workerThread);
        }
    }

    public void run() {
        try {
            new Worker().listenClient(socket);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public WorkerThread(Socket socket) {
        this.socket = socket;
    }
}